package com.yxhl.zoume.common.ui.activity.base;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.MotionEvent;

import com.umeng.message.PushAgent;
import com.yxhl.zoume.R;
import com.yxhl.zoume.ZouMeApplication;
import com.yxhl.zoume.account.event.UserLogoutEvent;
import com.yxhl.zoume.data.http.model.account.ZMAccount;
import com.yxhl.zoume.data.rxbus.RxBus;
import com.yxhl.zoume.di.component.base.AppComponent;
import com.yxhl.zoume.di.module.ActivityModule;
import com.yxhl.zoume.domain.event.LoginInvalidEvent;
import com.yxhl.zoume.navigator.Navigator;
import com.yxhl.zoume.utils.AccountUtils;
import com.yxhl.zoume.utils.ActivityControlUtils;

import javax.inject.Inject;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.Subscription;
import rx.functions.Action1;
import rx.subscriptions.CompositeSubscription;


/**
 * Created by Xboy on 16/2/24.
 * 完成依赖注入,控件绑定,Fragment基本操作,RxBus生命周期管理
 */
public abstract class BaseActivity extends AppCompatActivity {

    private static final String TAG = "BaseActivity";
    @Inject
    public Navigator navigator; //如果子类不注入,而使用navigator会报空指针 by sugarya
    protected Context mBaseContext;
    /**
     * RxBus回调设置
     */
    private CompositeSubscription mCompositeSubscription;
    private Unbinder mUnBinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBaseContext = this;
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        // 设置ContentView
        setContentView(getLayoutResId());
        // 初始化ButterKnife
        initButterKnife();
        // 初始化注入器
        initializeInjector();


    }

    @Override
    protected void onResume() {
        super.onResume();
        // RxBus
        onLoginInvalidRxBusEvent();

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (null != mCompositeSubscription && !mCompositeSubscription.isUnsubscribed()) {
            mCompositeSubscription.unsubscribe();
            mCompositeSubscription = null;
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityControlUtils.remove(this);
        if (mUnBinder != null) {
            mUnBinder.unbind();
        }
    }

    /**
     * author vhawk
     * umeng推送 打点统计
     * 统计应用启动数据
     */
    private void startUmengAnalyse() {
        PushAgent.getInstance(this).onAppStart();
    }

    public AppComponent getAppComponent() {
        return ((ZouMeApplication) getApplication()).getAppComponent();
    }

    /**
     * RxBus回调
     * <p/>
     * Ethan
     */
    private void onLoginInvalidRxBusEvent() {
        getCompositeSubscription().add(toSubscription(LoginInvalidEvent.class,
                new Action1<LoginInvalidEvent>() {
                    @Override
                    public void call(LoginInvalidEvent loginInvalidEvent) {
//                        CommonDialogFragment dialogFragment = CommonDialogFragment.newInstance(CommonDialogType.LOGIN);
//                        dialogFragment.show(getSupportFragmentManager(), dialogFragment.getClass().getSimpleName());
                        processAllopatricLogin();
                        getAppComponent().navigator().navigateToMobileLogin(mBaseContext);

                    }
                }
        ));
    }

    private void processAllopatricLogin() {
        ZMAccount account = AccountUtils.getInstance(this).getAccount();
        if (null != account) {
            String accessToken = account.getAccessToken();
            String accountName = account.getAccountName();
            if (!TextUtils.isEmpty(accessToken)  || !TextUtils.isEmpty(accountName)) {
                RxBus.getInstance().send(new UserLogoutEvent());
            }
        }
    }

    protected <T> Subscription toSubscription(Class<T> type, Action1<T> action1) {
        return RxBus.getInstance().toSubscription(type, action1);
    }

    protected <T> Subscription toSubscription(Class<T> type, Action1<T> action1, Action1<Throwable> errorAction1) {
        return RxBus.getInstance().toSubscription(type, action1, errorAction1);
    }

    /**
     * 返回subscription
     *
     * @return
     */
    public CompositeSubscription getCompositeSubscription() {
        if (null == mCompositeSubscription) {
            mCompositeSubscription = new CompositeSubscription();
        }
        return mCompositeSubscription;
    }

    protected ActivityModule getActivityModule() {
        return new ActivityModule(this);
    }

    /**
     * 获取ContentView
     *
     * @return
     */
    protected abstract
    @LayoutRes
    int getLayoutResId();

    /**
     * 初始化ButterKnife
     */
    private void initButterKnife() {
        try {
            mUnBinder = ButterKnife.bind(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化Injector(Component)
     */
    protected abstract void initializeInjector();


    /**
     * 向当前Activity添加Fragment
     *
     * @param containerId
     * @param fragment
     */
    public void addFragment(int containerId, Fragment fragment) {
        if (containerId != 0 && fragment != null) {
            FragmentManager fragmentManager = this.getSupportFragmentManager();
            if (fragmentManager != null) {
                Fragment fragmentByTag = fragmentManager.findFragmentByTag(Fragment.class.getSimpleName());
                if (fragmentByTag == null) {
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    if (fragmentTransaction != null) {
                        fragmentTransaction.add(containerId, fragment, Fragment.class.getSimpleName());
                        fragmentTransaction.commitAllowingStateLoss();
                    }
                }
            }
        }
    }


    /**
     * 向当前Activity置换Fragment
     *
     * @param containerId
     * @param fragment
     * @param addToBackStack
     */
    public void replaceFragment(int containerId, Fragment fragment, boolean addToBackStack) {
        replaceFragment(containerId, fragment, addToBackStack, false);
    }

    /**
     * 动画置换Fragment
     *
     * @param containerId
     * @param fragment
     * @param addToBackStack
     */
    public void replaceFragmentWithAnimation(int containerId, Fragment fragment, boolean addToBackStack) {
        replaceFragment(containerId, fragment, addToBackStack, true);
    }

    /**
     * Activity内,同级 动画 置换Fragment
     *
     * @param containerId
     * @param fragment
     * @param addToBackStack
     */
    private void replaceFragment(int containerId, Fragment fragment, boolean addToBackStack, boolean isAnimation) {
        if (containerId != 0 && fragment != null) {
            FragmentManager fragmentManager = this.getSupportFragmentManager();
            if (fragmentManager != null) {
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                if (fragmentTransaction != null) {
                    if (isAnimation) {
                        fragmentTransaction.setCustomAnimations(R.anim.fragment_slide_right_enter, R.anim.noanimation);
                    }
                    if (addToBackStack) {
                        fragmentTransaction.addToBackStack(null);
                    }
                    fragmentTransaction.replace(containerId, fragment);
                    fragmentTransaction.commitAllowingStateLoss();
                }
            }
        }
    }

    /**
     * 向当前Activity添加Fragment并设置Tag
     *
     * @param containerId
     * @param fragment
     */
    protected void addFragment(int containerId, Fragment fragment, String tag) {
        if (containerId != 0 && fragment != null) {
            FragmentManager fragmentManager = this.getSupportFragmentManager();
            if (fragmentManager != null) {
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                if (fragmentTransaction != null) {
                    fragmentTransaction.add(containerId, fragment, tag);
                    fragmentTransaction.commit();
                }
            }
        }
    }
    /**
     * 替换fragment（hide隐藏之前的frg，保存实例）
     * @param fromFragment 当前fragment
     * @param toFragment 开启的fragment
     * @param containerId 布局
     * @param addToBackStack 是否加入回退栈
     * @param toFragmentTag 开启的fragment设置tag
     */
    public void replaceFragment(Fragment fromFragment, Fragment toFragment, int containerId, boolean addToBackStack, @NonNull String toFragmentTag) {
        if (fromFragment != null && toFragment != null && containerId != 0) {
            FragmentManager fragmentManager = this.getSupportFragmentManager();
            if (fragmentManager != null) {
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                if (addToBackStack)
                    fragmentTransaction.addToBackStack(null);
                if (!toFragment.isAdded() && !toFragmentTag.equals(toFragment.getTag())) {
                    fragmentTransaction.hide(fromFragment).add(containerId, toFragment,toFragmentTag).commit();
                } else
                    fragmentTransaction.hide(fromFragment).show(toFragment).commit();
            }
        }
    }

}
